﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace BDV.TfsCustomActivities.BuildTasks
{
    internal static class ShfbprojHelper
    {
        public static void RedirrigeCheminsDocumentSource(FileInfo inputFile, DirectoryInfo outputBinariesFolder)
        {
            if (!inputFile.Exists)
                throw new FileNotFoundException(string.Format("Shfbproj transform for build > input file {0} not found !", inputFile.FullName), inputFile.FullName);

            var lstDocProjects = new List<FileInfo>();

            if (inputFile.Extension == ".sln")
            {
                var sln = new VsSolution(inputFile.FullName);
                foreach (var localProject in sln.Projects)
                {
                    var prjPath = Path.Combine(inputFile.Directory.FullName, localProject.RelativePath);
                    if (prjPath.EndsWith(".shfbproj") && File.Exists(prjPath))
                        lstDocProjects.Add(new FileInfo(prjPath));
                }
            }
            else if (inputFile.Extension == ".shfbproj")
            {
                lstDocProjects.Add(inputFile);
            }

            foreach (var path in lstDocProjects)
                ShfbprojHelper.TraiteShfbFile(path, outputBinariesFolder);

        }

        private static void TraiteShfbFile(FileInfo shfbprojPath, DirectoryInfo realFolderPath)
        {
            XElement shfbdoc = XElement.Load(shfbprojPath.FullName);

            var docSrcs = shfbdoc.Elements().Where(x => x.Name.LocalName == "PropertyGroup" && x.Elements().Any(y => y.Name.LocalName == "DocumentationSources")).ToList();

            var docSrc = docSrcs.FirstOrDefault();

            if (docSrc != null)
            {
                var documentationSourceToChange = docSrc.Elements().First(x => x.Name.LocalName == "DocumentationSources").Elements();
                foreach (var item in documentationSourceToChange)
                {
                    var pathXAttr = item.Attribute("sourceFile");
                    pathXAttr.Value = Path.Combine(realFolderPath.FullName, new System.IO.FileInfo(pathXAttr.Value).Name);
                }

                shfbprojPath.IsReadOnly = false;
                shfbprojPath.Refresh();

                shfbdoc.Save(shfbprojPath.FullName);
            }
        }
    }
}
